import hashlib
import json
import random
import time

import requests
import xmltodict

from shop.conf import wx1_token, wx1_access_token_redis_key, wx1_appid, wx1_appsecret
from shop.util.mylogger import Alogger, Blogger
from shop.util.redis_util import RedisUtil
from shop.util.sqlhandler import MysqlHandler


class WXHandler:
    '''
    微信操作类
    '''

    def __init__(self):
        self.text = "text"
        self.event = "event"
        self.event_click = 'CLICK'
        self.button_one = "RANDOM_PIC"
        self.post_data_dict = None
        self.me_id = None
        self.user_id = None
        self.resp = 'success'
        self.wx_access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" \
                                   "&appid={}&secret={}"
        self.wx_menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={}"

    def check_wx_reqeust(self, signature, timestamp, nonce):
        '''
        验证请求是否来自微信
        :return:
        '''
        list1 = [wx1_token, timestamp, nonce]
        list1.sort()
        list2 = ''.join(list1)
        sha1 = hashlib.sha1()
        sha1.update(list2.encode('utf-8'))
        hashcode = sha1.hexdigest()
        Alogger.info(hashcode)
        if hashcode == signature:
            return True
        else:
            return False

    def get_access_token(self):
        '''
        获取微信的access_token
        :return:
        '''
        ru = RedisUtil()
        redis_access_token = ru.get_str(wx1_access_token_redis_key)
        Alogger.debug("redis中获取的access_token:")
        Alogger.debug(redis_access_token)
        if not redis_access_token:
            res = requests.get(self.wx_access_token_url.format(wx1_appid, wx1_appsecret))
            Alogger.debug(res.text)
            res_json = res.json()
            access_token = res_json.get("access_token")
            if not access_token:
                raise Exception(res.text)
            ru.set_str(wx1_access_token_redis_key, access_token, 60 * 60 * 2)
            return access_token
        return redis_access_token

    def create_menu(self):
        '''
        创建微信菜单
        :return:
        '''
        access_token = self.get_access_token()
        data = {
            "button": [
                {
                    "type": "click",
                    "name": "随机图片",
                    "key": "RANDOM_PIC"
                }
            ]
        }
        res = requests.post(self.wx_menu_create_url.format(access_token), data=json.dumps(data, ensure_ascii=False).
                            encode('utf-8'))
        Alogger.debug(res.text)

    def analysis_wx_data(self, resp_data):
        '''
        解析微信发来的事件消息
        :return:
        '''
        post_data_dict = xmltodict.parse(resp_data).get('xml')
        self.post_data_dict = post_data_dict
        self.me_id = self.post_data_dict.get('ToUserName')
        self.user_id = self.post_data_dict.get('FromUserName')
        Blogger.debug(self.post_data_dict)
        # 获取类型
        MsgType = post_data_dict.get('MsgType')
        Blogger.debug(MsgType)
        if MsgType == self.text:
            pass
        elif MsgType == self.event:
            self.parse_event()

        Blogger.debug(self.resp)
        return self.resp

    def parse_event(self):
        '''
        解析event
        :param post_data_dict:
        :return:
        '''
        event_type = self.post_data_dict.get('Event')
        if event_type == self.event_click:
            self.parse_event_click()

    def parse_event_click(self):
        '''
        解析event的click事件
        :param post_data_dict:
        :return:
        '''
        event_key = self.post_data_dict.get('EventKey')
        if event_key == self.button_one:
            self.get_random_pic_url()

    def get_random_pic_url(self):
        '''
        获取随机图片url
        :return:
        '''
        # randid = random.randint(1, 136991)
        # sqlme = MysqlHandler()
        # sql_text = "SELECT url FROM  all_bizhi ab where id={};".format(randid)
        # res = sqlme.fetchone(sql_text)
        # if not res:
        #     randid = random.randint(1, 136991)
        #     sql_text = "SELECT url FROM  all_bizhi ab where id={};".format(randid)
        #     res = sqlme.fetchone(sql_text)
        pic_url = "骗你的！没有图片！哈哈"

        self.resp = self.make_resp(pic_url)

    def make_resp(self, msg, resp_type="text"):
        '''
        创造返回结果
        :return:
        '''
        now_ts = time.time()
        res = ""
        if resp_type == "text":
            # 返回文本消息
            res = '''
            <xml>
              <ToUserName><![CDATA[{}]]></ToUserName>
              <FromUserName><![CDATA[{}]]></FromUserName>
              <CreateTime>{}</CreateTime>
              <MsgType><![CDATA[text]]></MsgType>
              <Content><![CDATA[{}]]></Content>
            </xml>
            '''.format(self.user_id, self.me_id, now_ts, msg)
        return res
